package com.itheima.controller;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取用户列表
     * @return
     */
    @GetMapping
    public Result getUserList() {
        List<User> userList = userMapper.selectList(null);
        return  Result.success(userList);
    }

    /**
     * 根据id获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getUserById(@PathVariable Integer id) {
        User user = userMapper.selectById(id);
        return Result.success(user);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping
    public Result addUser(@RequestBody User user) {
        userMapper.insert(user);
        return Result.success();
    }

    /**
     * 根据id更新用户信息
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    public Result updateUser(@PathVariable Integer id, @RequestBody User user) {
        user.setId(id);
        userMapper.updateById(user);
        return Result.success();
    }


    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        userMapper.deleteById(id);
        return Result.success();
    }
}

